#include "topcvt_string.hpp"
#include "topcvt_policycontext.hpp"

namespace topcvt
{
    PolicyContext::PolicyContext(PktObject& obj, PolicyImp& policy, PolicyCfg& policyCfg)
        : m_obj(obj)
        , m_policy(policy)
        , m_policyCfg(policyCfg)
        , m_dict(policyCfg.get("dictfile"))
    {
        m_objStack.push(obj);
    }

    PolicyImp& PolicyContext::getPolicy() { return m_policy; }
    PolicyCfg& PolicyContext::getPolicyCfg() { return m_policyCfg; }
    PktObject& PolicyContext::getObj() { return m_obj; }

    string PolicyContext::getPolicyAttr(const string& attr, const string& defVal)
    {
        string value = getPolicyCfg().get(attr);
        return !value.empty() ? value : defVal;
    }

    string PolicyContext::getNodeAttr(AttributeableCfg& t, const string& attr, const string& defVal)
    {
        string value = t.get(attr);
        if (value.empty())
            value = getPolicyAttr(attr);
        return value.empty() && !defVal.empty() ? defVal : value;
    }

    string PolicyContext::getDictValue(const string& sDictId, const string& sSrcValue)
    {
        return m_dict.getDictValue(sDictId,sSrcValue);
    }

    string PolicyContext::getFldVal(PolicyContext& ctx, const string& key)
    {
        if(key.empty())
            return string();
        auto& obj = ctx.top();
        return obj[key].asString();
    }

    void PolicyContext::setFldVal(PolicyContext& ctx, const string& key, const string& value)
    {
        if(key.empty())
            return;
        auto& obj = ctx.top();
        obj[key] = value;
    }

}